package com.learning.imoney;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.learning.imoney.db.Bill;

import java.util.List;

public class BillAdapter extends RecyclerView.Adapter<BillAdapter.BillViewHolder> {
    private List<Bill> billList;
    private Context context;

    public BillAdapter(List<Bill> billList, Context context) {
        this.billList = billList;
        this.context = context;

    }

    @NonNull
    @Override
    public BillViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 载入单个账单项布局
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_bill, parent, false);
        return new BillViewHolder(itemView);
    }

    @SuppressLint("ResourceAsColor")
    @Override
    public void onBindViewHolder(@NonNull BillViewHolder holder, int position) {
        Bill bill = billList.get(position);
        if (bill.getTypeId() == 1) {
            holder.tvType.setText("收入");
            holder.tvAmount.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.teal_700));
        } else if (bill.getTypeId() == 0) {
            holder.tvType.setText("支出");
            holder.tvAmount.setTextColor(holder.itemView.getContext().getResources().getColor(R.color.black));
        }
        holder.tvAmount.setText(String.format("%.2f元", bill.getAmount()));
        holder.tvDate.setText(bill.getDate());
        holder.tvNote.setText(bill.getNote());

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, BillEdit.class);
                intent.putExtra("id", bill.getId());
                intent.putExtra("type", bill.getTypeId());
                intent.putExtra("money", bill.getAmount());
                intent.putExtra("date", bill.getDate());
                intent.putExtra("note", bill.getNote());
                context.startActivity(intent);
            }
        });


    }


    @Override
    public int getItemCount() {
        return billList.size();
    }

    // 自定义ViewHolder
    public static class BillViewHolder extends RecyclerView.ViewHolder {

        public TextView tvType;
        public TextView tvAmount;
        public TextView tvDate;
        public TextView tvNote;

        public BillViewHolder(@NonNull View itemView) {
            super(itemView);
            tvType = itemView.findViewById(R.id.tv_type);
            tvAmount = itemView.findViewById(R.id.tv_amount);
            tvDate = itemView.findViewById(R.id.tv_date);
            tvNote = itemView.findViewById(R.id.tv_note);
        }
    }
}



